<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <div class="section-header">
        <i class="el-icon-search"></i>
        <span>筛选条件</span>
      </div>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="选择测评任务">
              <el-select
                v-model="selectedTaskId"
                placeholder="请选择测评任务"
                @change="onTaskChange"
                style="width: 100%"
              >
                <el-option
                  v-for="task in taskList"
                  :key="task.id"
                  :label="task.taskName"
                  :value="task.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="选择区域">
              <el-cascader
                v-model="selectedDeptId"
                :options="filteredDeptList"
                :props="cascaderProps"
                placeholder="请选择区域"
                @change="onDeptChange"
                style="width: 100%"
                clearable
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 统计图表和表格区域 -->
    <div class="chart-table-container" v-if="selectedTaskId">
      <div class="section-header">
        <i class="el-icon-pie-chart"></i>
        <span>数据统计</span>
      </div>
      <el-row :gutter="20">
        <!-- 左侧图表区域 -->
        <el-col :span="12">
          <div class="chart-wrapper">
            <div id="healthPieChart" style="width: 100%; height: 220px;"></div>
          </div>
        </el-col>
        <!-- 右侧统计表格 -->
        <el-col :span="12">
          <div class="statistics-table">
            <el-table
              :data="statisticsTableData"
              border
              style="width: 100%"
            >
              <el-table-column prop="level" label="预警等级" align="center" />
              <el-table-column prop="count" label="人数" align="center" />
              <el-table-column prop="percentage" label="占比" align="center" />
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 列表筛选区域 -->
    <div class="table-filter-container">
      <div class="section-header section-header--small">
        <i class="el-icon-filter"></i>
        <span>列表筛选</span>
      </div>
      <el-form :inline="true" class="table-filter-form">
        <el-form-item label="姓名">
          <el-input
            v-model="queryParams.nickName"
            placeholder="请输入姓名"
            style="width: 200px"
            clearable
            @clear="handleTableFilter"
            @keyup.enter.native="handleTableFilter"
          />
        </el-form-item>
        <el-form-item label="等级判断方式">
          <el-select
            v-model="queryParams.levelJudge"
            placeholder="请选择等级判断方式"
            style="width: 180px"
            clearable
            @change="handleTableFilter"
          >
            <el-option label="测评预警" value="1" />
            <el-option label="二阶段访谈" value="2" />
            <el-option label="咨询评估" value="3" />
            <el-option label="综合评定" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleTableFilter">筛选</el-button>
          <el-button @click="handleClearFilter">清空</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button 
            type="success" 
            icon="el-icon-download" 
            @click="handleDownload"
            :loading="downloadLoading"
          >
            下载预警名单
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 数据表格区域 -->
    <div class="table-container">
      <div class="section-header">
        <i class="el-icon-document"></i>
        <span>预警名单</span>
        <div class="header-actions">
          <el-tag type="info" size="small">
            共 {{ total }} 条记录
          </el-tag>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="nickName" label="姓名" width="120" />
        <el-table-column prop="userName" label="学号" width="150" />
        <el-table-column prop="classzName" label="班级"/>
        <el-table-column prop="gradeName" label="年级"/>
        <el-table-column prop="schoolName" label="所属区域"/>
        <el-table-column prop="levelJudge" label="等级判断方式" width="120" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="getLevelJudgeTagType(scope.row.levelJudge)"
              size="small"
            >
              {{ getLevelJudgeText(scope.row.levelJudge) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warnLevel" label="预警等级">
          <template slot-scope="scope">
            <el-tag
              :type="getWarningTagType(scope.row.warnLevel)"
              size="small"
            >
              {{ getWarningLevelText(scope.row.warnLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isInterview" label="是否访谈" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isInterview === 1 ? 'success' : 'info'"
              size="small"
            >
              {{ scope.row.isInterview === 1 ? '已访谈' : '未访谈' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="测评时间"/>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              icon="el-icon-view"
              @click="viewDetail(scope.row)"
            >
              查看详情
            </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-delete"
              style="color: #f56c6c"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { listAssess } from '@/api/system/assess'
import { listDept } from '@/api/system/dept'
import { listWarn, getWarnStatistics, delWarn, exportWarn } from '@/api/system/warn'
import Pagination from '@/components/Pagination'

export default {
  components: {
    Pagination
  },
  name: 'ReportSearch',
  data() {
    return {
      loading: false,
      downloadLoading: false,
      // 表单数据
      queryForm: {
        selectedTaskId: null,
        selectedDeptId: null
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: null,
        deptId: null,
        grade: null,
        classz: null,
        nickName: null,
        levelJudge: null
      },
      // 表格数据
      tableData: [],
      total: 0,
      // 筛选数据
      taskList: [],
      deptList: [],
      filteredDeptList: [],
      selectedTaskId: null,
      selectedDeptId: null,
      // 级联选择器配置
      cascaderProps: {
        value: 'deptId',
        label: 'deptName',
        children: 'children',
        expandTrigger: 'hover',
        emitPath: false, // 只返回最后一级的值
        checkStrictly: true // 可以选择任意一级
      },
      // 图表实例
      healthPieChart: null,
      warningBarChart: null,
      // 统计数据
      statisticsData: null,
      statisticsTableData: []
    }
  },
  mounted() {
    console.log('组件加载完成，开始初始化数据')
    // 先加载部门数据，再加载任务数据
    this.getDeptList().then(() => {
      this.getTaskList()
    })
  },
  methods: {
    // 获取测评任务列表
    async getTaskList() {
      try {
        const response = await listAssess({ pageNum: 1, pageSize: 1000 })
        console.log('测评任务接口响应:', response)
        this.taskList = response.rows || []
        console.log('获取到的测评任务列表:', this.taskList)
        
        // 默认选择第一条数据
        if (this.taskList.length > 0) {
          this.selectedTaskId = this.taskList[0].id
          console.log('默认选择的任务ID:', this.selectedTaskId)
          this.onTaskChange(this.selectedTaskId)
        } else {
          console.warn('没有获取到测评任务数据')
          // 即使没有任务，也要显示部门数据
          this.filterDeptList()
        }
      } catch (error) {
        console.error('获取测评任务失败:', error)
        this.$modal.msgError('获取测评任务失败')
        // 发生错误时也要显示部门数据
        this.filterDeptList()
      }
    },
    // 获取部门列表
    async getDeptList() {
      try {
        const response = await listDept()
        console.log('部门接口响应:', response)
        
        if (response && response.data) {
          console.log('原始部门数据:', response.data)
          // 使用handleTree将数据转换为树形结构
          this.deptList = this.handleTree(response.data, 'deptId')
          console.log('转换后的部门树形数据:', this.deptList)
          
          // 如果没有选择任务，显示所有部门
          if (!this.selectedTaskId) {
            this.filteredDeptList = this.deptList
            console.log('没有选择任务，显示所有部门:', this.filteredDeptList)
          }
        } else {
          console.warn('部门接口返回数据为空')
        }
      } catch (error) {
        console.error('获取部门列表失败:', error)
        this.$modal.msgError('获取部门列表失败')
      }
    },
    // 任务选择变化
    onTaskChange(taskId) {
      this.selectedTaskId = taskId
      this.selectedDeptId = null
      this.filterDeptList()
      if (taskId) {
        this.getStatistics()
        // 自动初始化区域选择
        this.$nextTick(() => {
          this.initializeDeptSelection()
        })
        // 自动调用查询，重新获取表格数据
        this.handleSearch()
      }
    },
    // 筛选部门列表
    filterDeptList() {
      console.log('开始筛选部门列表')
      console.log('当前selectedTaskId:', this.selectedTaskId)
      console.log('当前deptList:', this.deptList)
      
      if (!this.selectedTaskId) {
        // 如果没有选择任务，显示所有部门
        this.filteredDeptList = this.deptList || []
        console.log('没有选择任务，显示所有部门:', this.filteredDeptList)
        return
      }
      
      const selectedTask = this.taskList.find(task => task.id === this.selectedTaskId)
      if (!selectedTask) {
        this.filteredDeptList = this.deptList || []
        console.log('未找到任务，显示所有部门')
        return
      }
      
      console.log('选中的任务:', selectedTask)
      
      if (!selectedTask.createDept) {
        // 如果没有createDept，显示所有部门
        console.log('任务没有createDept，显示所有部门')
        this.filteredDeptList = this.deptList || []
        return
      }
      
      const createDeptId = selectedTask.createDept
      console.log('任务的createDept:', createDeptId, '类型:', typeof createDeptId)
      
      // 根据crateDept筛选部门
      this.filteredDeptList = this.getFilteredDeptsByCreateDept(this.deptList, createDeptId)
      
      // 如果筛选后没有数据，则显示所有部门作为备用方案
      if (!this.filteredDeptList || this.filteredDeptList.length === 0) {
        console.warn('筛选后没有部门数据，使用所有部门作为备用方案')
        this.filteredDeptList = this.deptList || []
      }
      
      console.log('最终筛选后的部门列表:', this.filteredDeptList)
    },
    // 根据crateDept筛选部门
    getFilteredDeptsByCreateDept(depts, createDept) {
      console.log('开始筛选部门，createDept:', createDept)
      console.log('原始部门数据:', depts)
      
      if (!createDept) {
        console.log('createDept为空，返回所有部门')
        return depts || []
      }
      
      if (!depts || !Array.isArray(depts) || depts.length === 0) {
        console.log('部门数据为空，返回空数组')
        return []
      }
      
      let deptIds = []
      
      // 处理createDept可能是数组、逗号分隔字符串或单个ID的情况
      if (Array.isArray(createDept)) {
        deptIds = createDept.map(id => id.toString())
      } else if (typeof createDept === 'string' && createDept.includes(',')) {
        deptIds = createDept.split(',').map(id => id.trim())
      } else if (createDept) {
        deptIds = [createDept.toString()]
      }
      
      console.log('处理后的deptIds:', deptIds)
      
      if (deptIds.length === 0) {
        console.log('deptIds为空，返回所有部门')
        return depts
      }
      
      const result = this.filterDeptTreeByCreateDeptIds(depts, deptIds)
      console.log('筛选结果:', result)
      
      return result && result.length > 0 ? result : depts
    },
    
    // 根据crateDept部门ID筛选树形数据，只返回指定部门及其子级
    filterDeptTreeByCreateDeptIds(depts, createDeptIds) {
      console.log('开始筛选树形数据，createDeptIds:', createDeptIds)
      
      if (!depts || !createDeptIds || !createDeptIds.length) {
        console.log('参数不合法，返回空数组')
        return []
      }
      
      // 递归查找指定的createDept部门
      const findCreateDept = (deptList) => {
        for (const dept of deptList) {
          if (!dept || dept.deptId === undefined || dept.deptId === null) {
            console.log('部门数据不合法:', dept)
            continue
          }
          
          const deptId = dept.deptId.toString()
          console.log('检查部门ID:', deptId, '是否在createDeptIds中')
          
          if (createDeptIds.includes(deptId)) {
            // 找到createDept部门，返回该部门及其完整的子部门树
            console.log('找到匹配的createDept部门:', dept)
            return this.deepCloneDept(dept)
          }
          
          // 递归查找子部门
          if (dept.children && dept.children.length) {
            const found = findCreateDept(dept.children)
            if (found) {
              return found
            }
          }
        }
        
        return null
      }
      
      const foundDept = findCreateDept(depts)
      const result = foundDept ? [foundDept] : []
      console.log('最终筛选结果:', result)
      return result
    },
    
    // 深拷贝部门对象
    deepCloneDept(dept) {
      if (!dept) return null
      
      try {
        return JSON.parse(JSON.stringify(dept))
      } catch (error) {
        console.error('深拷贝部门对象失败:', error)
        return { ...dept }
      }
    },
    
    // 将列表数据构建为树形结构
    handleTree(data, id, parentId, children) {
      const config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
      }
      
      const childrenListMap = {}
      const nodeIds = {}
      const tree = []
      
      for (const d of data) {
        const parentId = d[config.parentId]
        if (!childrenListMap[parentId]) {
          childrenListMap[parentId] = []
        }
        nodeIds[d[config.id]] = d
        childrenListMap[parentId].push(d)
      }
      
      for (const d of data) {
        const parentId = d[config.parentId]
        if (!nodeIds[parentId]) {
          tree.push(d)
        }
      }
      
      for (const t of tree) {
        this.adaptToChildrenList(t, childrenListMap, config)
      }
      
      return tree
    },
    
    // 适配子节点列表
    adaptToChildrenList(t, childrenListMap, config) {
      if (childrenListMap[t[config.id]]) {
        t[config.childrenList] = childrenListMap[t[config.id]]
        for (const c of t[config.childrenList]) {
          this.adaptToChildrenList(c, childrenListMap, config)
        }
      }
    },
    
    // 初始化区域选择
    async initializeDeptSelection() {
      if (this.filteredDeptList && this.filteredDeptList.length > 0) {
        // 获取第一个可用的部门节点
        const firstNode = this.getFirstAvailableNode(this.filteredDeptList)
        
        if (firstNode && firstNode.deptId) {
          this.selectedDeptId = firstNode.deptId
          console.log('自动选择区域:', firstNode.deptName, 'ID:', firstNode.deptId)
          
          // 选择区域后重新获取统计数据
          if (this.selectedTaskId) {
            this.getStatistics()
          }
        } else {
          console.log('未找到可用的区域节点')
        }
      } else {
        console.log('没有可显示的区域数据')
      }
    },
    
    // 获取第一个可用的节点（优先选择有子节点的父级节点）
    getFirstAvailableNode(tree) {
      if (!tree || !tree.length) return null
      
      const firstNode = tree[0]
      // 如果第一个节点有子节点，则返回它作为父级节点
      if (firstNode.children && firstNode.children.length > 0) {
        return firstNode
      }
      
      // 如果第一个节点没有子节点，则继续查找其他节点
      for (let i = 1; i < tree.length; i++) {
        if (tree[i].children && tree[i].children.length > 0) {
          return tree[i]
        }
      }
      
      // 如果都没有子节点，则返回第一个节点
      return firstNode
    },
    // 区域选择变化
    onDeptChange(value) {
      console.log('区域选择变化:', value)
      this.selectedDeptId = value
      
      // 区域变化后重新获取统计数据和列表数据
      if (this.selectedTaskId) {
        console.log('区域变化，重新加载统计数据和列表数据')
        this.getStatistics()
        this.handleSearch() // 重新构建查询参数并获取列表数据
      }
    },
    // 查询
    handleSearch() {
      this.queryParams.pageNum = 1
      this.queryParams.taskId = this.selectedTaskId
      
      // 清空之前的筛选参数
      delete this.queryParams.deptId
      delete this.queryParams.grade
      delete this.queryParams.classz
      
      // 如果选择了区域，添加区域筛选条件
      if (this.selectedDeptId) {
        const deptInfo = this.findDeptInfoById(this.selectedDeptId)
        console.log('查询时获取的部门信息:', deptInfo)
        
        if (deptInfo) {
          // 始终添加选中的deptId
          this.queryParams.deptId = this.selectedDeptId
          
          // 根据部门类型决定添加哪些参数
          if (deptInfo.type === '5' || deptInfo.type === 5) {
            // 选择年级：传递 deptId 和 grade
            this.queryParams.grade = deptInfo.deptId
            console.log('选择年级，添加参数: deptId=' + this.queryParams.deptId + ', grade=' + this.queryParams.grade)
          } else if (deptInfo.type === 6 || deptInfo.type === '6') {
            // 选择班级：传递 deptId、classz 和对应的 grade
            this.queryParams.classz = deptInfo.deptId
            if (deptInfo.grade) {
              this.queryParams.grade = deptInfo.grade
            }
            console.log('选择班级，添加参数: deptId=' + this.queryParams.deptId + ', classz=' + this.queryParams.classz + ', grade=' + (this.queryParams.grade || '无'))
          } else {
            // 选择学校/机构：只传递 deptId
            console.log('选择学校/机构，只添加参数: deptId=' + this.queryParams.deptId)
          }
        }
      }
      
      console.log('最终查询参数:', this.queryParams)
      this.getList()
    },
    // 列表筛选
    handleTableFilter() {
      console.log('列表筛选参数:', {
        nickName: this.queryParams.nickName,
        levelJudge: this.queryParams.levelJudge
      })
      // 重置到第一页并重新查询
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 清空列表筛选
    handleClearFilter() {
      console.log('清空列表筛选条件')
      this.queryParams.nickName = null
      this.queryParams.levelJudge = null
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      // 保持当前选择的测评任务不变
      const currentTaskId = this.selectedTaskId
      
      // 重置区域选择
      this.selectedDeptId = null
      this.queryForm.selectedDeptId = null
      
      // 重置查询参数，但保持taskId
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        taskId: currentTaskId,
        deptId: null,
        grade: null,
        classz: null,
        nickName: null,
        levelJudge: null
      }
      
      // 如果有选择的任务，重新筛选部门列表并获取统计数据
      if (currentTaskId) {
        this.filterDeptList()
        this.getStatistics()
        // 重新获取列表数据
        this.getList()
      } else {
        // 如果没有选择任务，清空相关数据
        this.filteredDeptList = []
        this.tableData = []
        this.total = 0
        this.statisticsTableData = []
        this.destroyCharts()
      }
    },
    // 获取列表数据
    async getList() {
      if (!this.selectedTaskId) {
        this.$modal.msgWarning('请先选择测评任务')
        return
      }
      
      console.log('获取列表数据，查询参数:', this.queryParams)
      
      this.loading = true
      try {
        const response = await listWarn(this.queryParams)
        console.log('列表数据响应:', response)
        this.tableData = response.rows || []
        this.total = response.total || 0
        console.log('获取到的表格数据数量:', this.tableData.length)
      } catch (error) {
        console.error('获取列表数据失败:', error)
        this.$modal.msgError('获取列表数据失败')
      } finally {
        this.loading = false
      }
    },
    // 获取统计数据
    async getStatistics() {
      if (!this.selectedTaskId) return
      
      try {
        const params = {
          taskId: this.selectedTaskId
        }
        
        // 如果选择了区域，添加区域筛选条件
        if (this.selectedDeptId) {
          const deptInfo = this.findDeptInfoById(this.selectedDeptId)
          console.log('统计接口获取的部门信息:', deptInfo)
          
          if (deptInfo) {
            // 始终传递选中的deptId
            params.deptId = this.selectedDeptId
            
            // 根据部门类型决定传递哪些参数
            if (deptInfo.type === '5' || deptInfo.type === 5) {
              // 选择年级：传递 deptId 和 grade
              params.grade = deptInfo.deptId
              console.log('选择年级，传递参数: deptId=' + params.deptId + ', grade=' + params.grade)
            } else if (deptInfo.type === 6 || deptInfo.type === '6') {
              // 选择班级：传递 deptId、classz 和对应的 grade
              params.classz = deptInfo.deptId
              if (deptInfo.grade) {
                params.grade = deptInfo.grade
              }
              console.log('选择班级，传递参数: deptId=' + params.deptId + ', classz=' + params.classz + ', grade=' + (params.grade || '无'))
            } else {
              // 选择学校/机构：只传递 deptId
              console.log('选择学校/机构，只传递参数: deptId=' + params.deptId)
            }
          }
        }
        
        console.log('统计接口最终请求参数:', params)
        const response = await getWarnStatistics(params)
        this.statisticsData = response.data
        this.generateStatisticsTableData()
        this.$nextTick(() => {
          this.initHealthPieChart()
        })
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$modal.msgError('获取统计数据失败')
      }
    },
    
    // 查找部门信息及其父级信息
    findDeptInfoById(deptId) {
      if (!deptId || !this.deptList) {
        console.log('参数不合法，deptId:', deptId, 'deptList:', this.deptList)
        return null
      }
      
      console.log('开始查找部门ID:', deptId, '类型:', typeof deptId)
      
      // 递归查找部门
      const findDept = (depts, targetId, parentChain = []) => {
        for (const dept of depts) {
          if (!dept || dept.deptId === undefined) {
            console.log('部门数据不合法:', dept)
            continue
          }
          
          const currentDeptId = dept.deptId.toString()
          console.log('检查部门:', dept.deptName, 'ID:', currentDeptId, '类型:', dept.type)
          
          if (currentDeptId === targetId.toString()) {
            // 找到目标部门
            console.log('找到目标部门:', dept)
            console.log('父级链条:', parentChain)
            
            const result = {
              ...dept,
              parentChain: parentChain
            }
            
            // 根据部门类型和父级信息设置相应字段
            if (dept.type === '5' || dept.type === 5) {
              // 当前部门是年级
              result.grade = dept.deptId
              console.log('当前部门是年级，设置grade:', dept.deptId)
            } else if (dept.type === '6' || dept.type === 6) {
              // 当前部门是班级
              result.classz = dept.deptId
              console.log('当前部门是班级，设置classz:', dept.deptId)
              
              // 查找父级年级（在parentChain中递归查找类型为5的部门）
              for (let i = parentChain.length - 1; i >= 0; i--) {
                const parent = parentChain[i]
                if (parent.type === '5' || parent.type === 5) {
                  result.grade = parent.deptId
                  console.log('找到父级年级，设置grade:', parent.deptId, '年级名称:', parent.deptName)
                  break
                }
              }
              
              // 如果没有找到父级年级，警告一下
              if (!result.grade) {
                console.warn('班级部门没有找到父级年级，parentChain:', parentChain)
              }
            } else {
              // 对于其他类型的部门，查找最近的年级和班级父级
              for (let i = parentChain.length - 1; i >= 0; i--) {
                const parent = parentChain[i]
                if ((parent.type === '5' || parent.type === 5) && !result.grade) {
                  result.grade = parent.deptId
                  console.log('找到父级年级，设置grade:', parent.deptId)
                }
                if ((parent.type === '6' || parent.type === 6) && !result.classz) {
                  result.classz = parent.deptId
                  console.log('找到父级班级，设置classz:', parent.deptId)
                }
              }
            }
            
            console.log('最终部门信息:', result)
            return result
          }
          
          // 递归查找子部门
          if (dept.children && dept.children.length > 0) {
            const newParentChain = [...parentChain, dept]
            const found = findDept(dept.children, targetId, newParentChain)
            if (found) return found
          }
        }
        
        return null
      }
      
      const result = findDept(this.deptList, deptId)
      console.log('查找部门信息结果:', result)
      return result
    },
    // 生成统计表格数据
    generateStatisticsTableData() {
      if (!this.statisticsData || !this.statisticsData.data1) {
        this.statisticsTableData = []
        return
      }
      
      const total = this.statisticsData.data1.reduce((sum, item) => sum + item.count, 0)
      
      this.statisticsTableData = this.statisticsData.data1.map(item => {
        const percentage = total > 0 ? Math.round((item.count / total) * 100) : 0
        return {
          level: item.name,
          count: item.count,
          percentage: percentage + '%'
        }
      })
    },
    // 初始化健康状况饼图
    initHealthPieChart() {
      if (!this.statisticsData || !this.statisticsData.data1) return
      
      const chartDom = document.getElementById('healthPieChart')
      if (!chartDom) return
      
      if (this.healthPieChart) {
        this.healthPieChart.dispose()
      }
      
      this.healthPieChart = echarts.init(chartDom)
      
      const data = this.statisticsData.data1.map(item => ({
        name: item.name,
        value: item.count
      }))
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '心理健康状况',
            type: 'pie',
            radius: '50%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            itemStyle: {
              color: function(params) {
                const colors = ['#67C23A', '#E6A23C', '#F56C6C', '#909399']
                return colors[params.dataIndex] || '#409EFF'
              }
            }
          }
        ]
      }
      
      this.healthPieChart.setOption(option)
    },

    // 销毁图表
    destroyCharts() {
      if (this.healthPieChart) {
        this.healthPieChart.dispose()
        this.healthPieChart = null
      }
    },
    // 获取预警标签类型
    getWarningTagType(level) {
      const typeMap = {
        '心理健康良好': 'success',
        '1级预警': 'warning',
        '2级预警': 'danger',
        '3级预警': 'danger'
      }
      return typeMap[level] || 'info'
    },
    // 获取预警等级文本
    getWarningLevelText(level) {
      return level || '未知'
    },
    // 获取等级判断方式标签类型
    getLevelJudgeTagType(levelJudge) {
      const typeMap = {
        '1': 'warning',    // 测评预警
        '2': 'primary',    // 二阶段访谈
        '3': 'info',       // 咨询评估
        '4': 'success'     // 综合评定
      }
      return typeMap[levelJudge] || 'info'
    },
    // 获取等级判断方式文本
    getLevelJudgeText(levelJudge) {
      const textMap = {
        '1': '测评预警',
        '2': '二阶段访谈',
        '3': '咨询评估',
        '4': '综合评定'
      }
      return textMap[levelJudge] || '未知'
    },
    // 查看详情
    viewDetail(row) {
      // 跳转到详情页面
      this.$router.push({
        path: '/detail',
        query: {
          userId: row.userId,
          taskId: this.selectedTaskId
        }
      })
    },
    // 删除操作
    handleDelete(row) {
      this.$confirm('是否确认删除该条记录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRecord(row.id)
      }).catch(() => {
        // 用户取消操作
      })
    },
    // 执行删除
    async deleteRecord(id) {
      try {
        await delWarn(id)
        this.$modal.msgSuccess('删除成功')
        // 重新加载数据
        this.getList()
      } catch (error) {
        console.error('删除失败:', error)
        this.$modal.msgError('删除失败')
      }
    },
    // 下载预警名单
    async handleDownload() {
      if (!this.selectedTaskId) {
        this.$modal.msgWarning('请先选择测评任务')
        return
      }
      
      this.downloadLoading = true
      try {
        // 构建下载参数，使用和查询相同的参数
        const downloadParams = { ...this.queryParams }
        delete downloadParams.pageNum
        delete downloadParams.pageSize
        
        console.log('下载参数:', downloadParams)
        
        // 调用导出接口
        const response = await exportWarn(downloadParams)
        
        // 创建下载链接
        const blob = new Blob([response])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        
        // 生成文件名
        const now = new Date()
        const dateStr = now.toISOString().split('T')[0].replace(/-/g, '')
        const fileName = `预警名单_${dateStr}.xlsx`
        
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        this.$modal.msgSuccess('下载成功')
      } catch (error) {
        console.error('下载失败:', error)
        this.$modal.msgError('下载失败')
      } finally {
        this.downloadLoading = false
      }
    },
    // 导出Excel文件（已废弃，保留以供参考）
    exportToExcel(data) {
      // 定义导出列
      const headers = [
        '序号',
        '姓名', 
        '学号',
        '班级',
        '年级',
        '所属区域',
        '等级判断方式',
        '预警等级',
        '是否访谈',
        '测评时间'
      ]
      
      // 构建CSV内容
      let csvContent = '\uFEFF' // BOM for UTF-8
      csvContent += headers.join(',') + '\n'
      
      data.forEach((row, index) => {
        const rowData = [
          index + 1,
          row.nickName || '',
          row.userName || '',
          row.classzName || '',
          row.gradeName || '', 
          row.schoolName || '',
          this.getLevelJudgeText(row.levelJudge) || '',
          row.warnLevel || '',
          row.isInterview === 1 ? '已访谈' : '未访谈',
          row.createTime || ''
        ]
        csvContent += rowData.join(',') + '\n'
      })
      
      // 下载文件
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      
      // 生成文件名
      const now = new Date()
      const dateStr = now.toISOString().split('T')[0].replace(/-/g, '')
      const fileName = `预警名单_${dateStr}.csv`
      
      link.setAttribute('download', fileName)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      
      this.$modal.msgSuccess('下载成功')
    }
  },
  beforeDestroy() {
    this.destroyCharts()
  }
}
</script>

<style scoped>
/* 整体容器 */
.app-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 84px);
}

/* 区域标题样式 */
.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e2e8f0;
  position: relative;
}

.section-header i {
  font-size: 18px;
  color: #409EFF;
  margin-right: 8px;
}

.section-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.5px;
}

.section-header--small {
  margin-bottom: 16px;
  padding-bottom: 8px;
}

.section-header--small i {
  font-size: 16px;
}

.section-header--small span {
  font-size: 14px;
}

.header-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.section-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  border-radius: 1px;
}

/* 筛选容器 */
.filter-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.filter-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #67C23A, #E6A23C, #F56C6C);
  border-radius: 12px 12px 0 0;
}

.filter-container {
  position: relative;
}

/* 图表和统计容器 */
.chart-table-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

/* 统计表格样式 */
.statistics-table {
  text-align: center;
}

.statistics-table h3 {
  margin-bottom: 20px;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 图表容器 */
.chart-wrapper {
  text-align: center;
  position: relative;
}

.chart-wrapper::before {
  content: '';
  position: absolute;
  top: -10px;
  left: -10px;
  right: -10px;
  bottom: -10px;
  background: linear-gradient(45deg, #409EFF, #67C23A);
  border-radius: 16px;
  opacity: 0.1;
  z-index: -1;
}

.chart-wrapper h3 {
  margin-bottom: 20px;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 表格筛选容器 */
.table-filter-container {
  background: linear-gradient(145deg, #ffffff 0%, #f0f9ff 100%);
  padding: 20px 24px;
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.15);
  border-left: 5px solid #409EFF;
  position: relative;
  overflow: hidden;
}

.table-filter-container::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(64, 158, 255, 0.05));
  pointer-events: none;
}

.table-filter-form {
  margin-bottom: 0;
}

.table-filter-form .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.table-filter-form .el-form-item:last-child {
  margin-right: 0;
}

/* 表格容器 */
.table-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

/* 表单项样式 */
.el-form-item {
  margin-bottom: 0;
}

/* 按钮样式优化 */
.el-button {
  margin-left: 12px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-button:first-child {
  margin-left: 0;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.el-button--primary {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
  border: none;
}

.el-button--success {
  background: linear-gradient(45deg, #67C23A, #85ce61);
  border: none;
}

.el-button--warning {
  background: linear-gradient(45deg, #E6A23C, #ebb563);
  border: none;
}

/* 输入框和选择器样式 */
.el-input__inner,
.el-select .el-input__inner {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.el-input__inner:focus,
.el-select .el-input__inner:focus {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 级联选择器样式 */
.el-cascader {
  width: 100%;
}

.el-cascader .el-input__inner {
  border-radius: 8px;
}

/* 表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background: linear-gradient(145deg, #f8fafc 0%, #e2e8f0 100%);
  color: #2c3e50;
  font-weight: 600;
  border-bottom: 2px solid #e2e8f0;
}

.el-table tr:hover > td {
  background-color: rgba(64, 158, 255, 0.05) !important;
}

/* 标签样式优化 */
.el-tag {
  border-radius: 6px;
  font-weight: 500;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-tag--success {
  background: linear-gradient(45deg, #67C23A, #85ce61);
  color: white;
}

.el-tag--primary {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
  color: white;
}

.el-tag--warning {
  background: linear-gradient(45deg, #E6A23C, #ebb563);
  color: white;
}

.el-tag--danger {
  background: linear-gradient(45deg, #F56C6C, #f78989);
  color: white;
}

.el-tag--info {
  background: linear-gradient(45deg, #909399, #a6a9ad);
  color: white;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.el-pagination .el-pager li {
  border-radius: 6px;
  margin: 0 2px;
}

.el-pagination .el-pager li.active {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
  color: white;
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 16px;
  }
  
  .filter-container,
  .chart-table-container,
  .table-container {
    padding: 16px;
  }
  
  .table-filter-container {
    padding: 16px;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.filter-container,
.chart-table-container,
.table-filter-container,
.table-container {
  animation: fadeInUp 0.6s ease-out;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(45deg, #36a3f7, #409EFF);
}
</style>